package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.pay.service.WeixinPayService;
import com.changgou.util.Result;
import com.changgou.util.StatusCode;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author tang.qingbo
 * @Date 2020/9/6 22:01
 * @Version 1.0
 */
@RestController
@RequestMapping("/weixin/pay")
public class WeixinPayController {
    @Value("${mq.pay.queue.order}")
    private String queue;

    @Value("${mq.pay.exchange.order}")
    private String exchange;

    @Value("${mq.pay.routing.key}")
    private String routingKey;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private WeixinPayService weixinPayService;

    @RequestMapping("/notify/url")
    public String notifyUrl(HttpServletRequest request) {
        try {
            //返回信息存储在输入流中,获取数据流
            ServletInputStream in = request.getInputStream();
            //创建字节数组类型的输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            //定义缓存区
            byte[] buffer = new byte[1024];
            //定义读取有效字节长度len
            Integer len = 0;
            //从输入流中读取数据,并写入到输出流中
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            //关闭流
            out.close();
            in.close();

            //将输出流转为字节数组
            byte[] byteData = out.toByteArray();
            //字节数组转为字符串======取到的xml格式的数据
            String xmlData = new String(byteData, StandardCharsets.UTF_8);
            //将字符串转为map结构数据
            Map<String, String> stringMap = WXPayUtil.xmlToMap(xmlData);
            System.out.println("收到的结果数据: " + stringMap);

            /**
             * 将消息发送给rabbitmq
             */
            //rabbitTemplate.convertAndSend(exchange, routingKey, JSON.toJSONString(stringMap));
            //将attach数据转为map
            Map<String,String> queueMap = JSON.parseObject(stringMap.get("attach"), Map.class);
            rabbitTemplate.convertAndSend(queueMap.get("exchange"), queueMap.get("queue"), JSON.toJSONString(stringMap));

            //定义返回给微信服务器的数据
            Map<String, String> responseMap = new HashMap<>();
            responseMap.put("return_code", "SUCCESS");
            responseMap.put("return_msg", "OK");
            //将数据转为xml格式,响应给微信服务器
            return WXPayUtil.mapToXml(responseMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成支付二维码
     */
    @RequestMapping("/create/native")
    public Result createNative(@RequestParam Map<String,String> dataMap) {
        Map resultMap = weixinPayService.createNative(dataMap);
        return new Result(true, StatusCode.OK, "创建二维码预付订单成功", resultMap);
    }

    /**
     * 查询支付状态信息
     */
    @GetMapping("/status/query")
    public Result queryStatus(String outtradeno) {
        Map dataMap = weixinPayService.queryPayStatus(outtradeno);
        return new Result(true, StatusCode.OK, "查询订单状态成功", dataMap);
    }
}
